<!-- 规则管理 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="规则名称">
          <el-input
            v-model="queryParams.name"
            placeholder="规则名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目">
          <el-input
            v-model="queryParams.subject"
            placeholder="科目"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="toolbar-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </div>
    </div>

    <!-- 规则列表 -->
    <el-table v-loading="loading" :data="ruleList" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="规则名称" />
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column prop="totalScore" label="总分" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input
                v-model="ruleForm.ruleName"
                placeholder="请输入规则名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科目" prop="subject">
              <el-input v-model="ruleForm.subject" placeholder="请输入科目" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总分" prop="totalScore">
              <el-input-number
                v-model="ruleForm.totalScore"
                :min="1"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试时长" prop="duration">
              <el-input-number
                v-model="ruleForm.duration"
                :min="1"
                style="width: 100%"
                placeholder="请输入考试时长（分钟）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">题目配置</el-divider>
        <el-form-item prop="questionConfig">
          <div
            v-for="(item, index) in ruleForm.questionConfig"
            :key="index"
            class="question-config-item"
          >
            <div class="config-header">
              <span class="config-title">配置项 {{ index + 1 }}</span>
              <el-button
                type="danger"
                circle
                @click="removeQuestionConfig(index)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  :prop="'questionConfig.' + index + '.type'"
                  :rules="{
                    required: true,
                    message: '请选择题型',
                    trigger: 'change',
                  }"
                  label="题型"
                >
                  <el-select
                    v-model="item.type"
                    placeholder="请选择题型"
                    style="width: 100%"
                  >
                    <el-option label="单选题" value="single" />
                    <el-option label="多选题" value="multiple" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :prop="'questionConfig.' + index + '.difficulty'"
                  :rules="{
                    required: true,
                    message: '请选择难度',
                    trigger: 'change',
                  }"
                  label="难度"
                >
                  <el-select
                    v-model="item.difficulty"
                    placeholder="请选择难度"
                    style="width: 100%"
                  >
                    <el-option label="简单" value="easy" />
                    <el-option label="中等" value="medium" />
                    <el-option label="困难" value="hard" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  :prop="'questionConfig.' + index + '.count'"
                  :rules="{
                    required: true,
                    message: '请输入题目数量',
                    trigger: 'blur',
                  }"
                  label="题目数量"
                >
                  <el-input-number
                    v-model="item.count"
                    :min="1"
                    controls-position="right"
                    style="width: 100%"
                    placeholder="请输入题目数量"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :prop="'questionConfig.' + index + '.score'"
                  :rules="{
                    required: true,
                    message: '请输入分值',
                    trigger: 'blur',
                  }"
                  label="每题分值"
                >
                  <el-input-number
                    v-model="item.score"
                    :min="1"
                    controls-position="right"
                    style="width: 100%"
                    placeholder="请输入每题分值"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="add-config">
            <el-button type="primary" @click="addQuestionConfig" plain>
              <el-icon><Plus /></el-icon>
              添加题型配置
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getRules,
  getRule,
  addRule,
  updateRule,
  deleteRule,
  enableRule,
  disableRule,
} from "@/api/rule";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
  subject: "",
});

// 列表数据
const loading = ref(false);
const ruleList = ref([]);
const total = ref(0);

// 获取规则列表
const getRuleList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getRules(queryParams);
    ruleList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取规则列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getRuleList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.name = "";
  queryParams.subject = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getRuleList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getRuleList();
};

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = computed(() => (ruleForm.id ? "编辑规则" : "新增规则"));
const ruleFormRef = ref(null);
const ruleForm = reactive({
  id: null,
  ruleName: "",
  subject: "",
  totalScore: 100,
  duration: 120,
  questionConfig: [],
  status: 0,
});

// 表单校验规则
const rules = {
  ruleName: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  totalScore: [{ required: true, message: "请输入总分", trigger: "blur" }],
  duration: [{ required: true, message: "请输入考试时长", trigger: "blur" }],
  questionConfig: [
    {
      required: true,
      type: "array",
      min: 1,
      message: "请至少添加一个题型配置",
      trigger: "change",
    },
  ],
};

// 重置表单
const resetForm = () => {
  ruleForm.id = null;
  ruleForm.ruleName = "";
  ruleForm.subject = "";
  ruleForm.totalScore = 100;
  ruleForm.duration = 120;
  ruleForm.questionConfig = [];
  ruleForm.status = 0;
};

// 新增按钮点击
const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = async (row) => {
  try {
    const data = await getRule(row.id);
    // 解析配置并转换为前端格式
    let questionConfig = [];
    if (data.ruleConfig) {
      const config = JSON.parse(data.ruleConfig);
      questionConfig = config.questionTypes.map((item) => ({
        type: item.type,
        difficulty: item.difficulty,
        count: item.count,
        score: item.scorePerQuestion, // 将 scorePerQuestion 转换为 score
      }));
    }
    Object.assign(ruleForm, {
      ...data,
      questionConfig,
    });
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取规则详情失败：", error);
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;

  // 检查是否有题型配置
  if (!ruleForm.questionConfig || ruleForm.questionConfig.length === 0) {
    ElMessage.warning("请至少添加一个题型配置");
    return;
  }

  // 检查每个题型配置是否完整
  for (const config of ruleForm.questionConfig) {
    if (!config.type || !config.difficulty || !config.count || !config.score) {
      ElMessage.warning("请完整填写所有题型配置信息");
      return;
    }
  }

  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 转换配置格式以匹配后端期望的格式
        const ruleConfig = {
          questionTypes: ruleForm.questionConfig.map((config) => ({
            type: config.type,
            difficulty: config.difficulty,
            count: config.count,
            scorePerQuestion: config.score, // 将 score 转换为 scorePerQuestion
          })),
        };

        // 创建要提交的数据对象
        const submitData = {
          ...ruleForm,
          ruleConfig: JSON.stringify(ruleConfig),
        };
        delete submitData.questionConfig;

        if (ruleForm.id) {
          await updateRule(ruleForm.id, submitData);
          ElMessage.success("更新成功");
        } else {
          await addRule(submitData);
          ElMessage.success("添加成功");
        }
        dialogVisible.value = false;
        getRuleList();
      } catch (error) {
        console.error("保存规则失败：", error);
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message);
        } else {
          ElMessage.error("保存失败");
        }
      }
    }
  });
};

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该规则吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteRule(row.id);
        ElMessage.success("删除成功");
        getRuleList();
      } catch (error) {
        console.error("删除规则失败：", error);
      }
    })
    .catch(() => {});
};

// 添加题型配置
const addQuestionConfig = () => {
  ruleForm.questionConfig.push({
    type: "",
    difficulty: "",
    count: 1,
    score: 1,
  });
};

// 移除题型配置
const removeQuestionConfig = (index) => {
  ruleForm.questionConfig.splice(index, 1);
};

onMounted(() => {
  getRuleList();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.toolbar-buttons {
  margin-left: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.question-config-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #dcdfe6;
}

.config-title {
  font-size: 16px;
  font-weight: bold;
  color: #606266;
}

.delete-btn {
  margin-top: 0;
}

.add-config {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
  color: #606266;
}
</style>
